<?php
// +----------------------------------------------------------------------
// | 系统用户业务
// +----------------------------------------------------------------------
namespace app\admin\service;

use app\common\enum\BaseStatusEnum;
use app\common\model\SysUserModel;
use app\common\service\SysUserService as CommonSysUserService;
use app\common\service\SysUserRoleService as CommonSysUserRoleService;
use app\common\service\SysMenuService as CommonSysMenuService;
use app\common\enum\UserTypeEnum;
use app\common\enum\ErrorEnum;

class SysUserService {
    /**
     * 分页
     * @param  array  $param  请求参数
     * @return array
     */
    public static function page($param){
        $pageData = SysUserModel::page($param,['withoutField'=>'password']);

        foreach ($pageData as $v) {
            $v->statusName = BaseStatusEnum::getDescription($v['status']);
        }

        return $pageData;
    }


    /**
     * 新增数据
     * @param  array  $data  新增的数据
     * @return json
     */
    public static function save($data){
        if(SysUserModel::getByUsername($data['username'])){
            //如果存在
            return failure(ErrorEnum::USERNAME_IS_EXIST_CODE, ErrorEnum::USERNAME_IS_EXIST_DESC);
        }

        $data['password'] = createPassword($data['password']);
        $data['user_type'] = UserTypeEnum::SYSTEM_USER;
        $userId = CommonSysUserService::save($data);

        if ($data['roleIds']) {
            $roleList = [];
            foreach ($data['roleIds'] as $roleId) {
                array_push($roleList, ['user_id' => $userId, 'role_id' => $roleId]);
            }
            CommonSysUserRoleService::saveAll($roleList);
        }

        return $userId;
    }

    /**
     * 更新数据
     * @param  array  $data  更新的数据
     * @return json
     */
    public static function update($data){
        $sysUser = SysUserModel::find($data['id']);
        if(!$sysUser){
            return failure(ErrorEnum::USERNAME_IS_NOT_EXIST_CODE, ErrorEnum::USERNAME_IS_DISABLED_DESC);
        }

        //如果提交过来的账号跟数据库记录的账号不一样，说明当前提交过来的账号是修改过后的账号，因此这里需要验证修改过的账号是否在数据库里面已经存在
        if(isset($data['username']) && $data['username'] !== $sysUser->username){
            if(SysUserModel::getByUsername($data['username'])){
                //如果存在
                return failure(ErrorEnum::USERNAME_IS_EXIST_CODE, ErrorEnum::USERNAME_IS_DISABLED_DESC);
            }
        }

        //加密
        if(isset($data['password']) && !empty($data['password'])){
            $data['password'] = createPassword($data['password']);
        }

        $sysUser->save($data);

        CommonSysUserRoleService::destroyByUserId($sysUser->id);
        if (isset($data['roleIds']) && $data['roleIds']) {
            $roleList = [];
            foreach ($data['roleIds'] as $roleId) {
                array_push($roleList, ['user_id' => $sysUser->id, 'role_id' => $roleId]);
            }
            CommonSysUserRoleService::saveAll($roleList);
        }

        return $sysUser->id;
    }

    /**
     * 详情
     * @param  array  $id  数据ID
     * @return json
     */
    public static function info($id){
        $data = CommonSysUserService::info($id);

        $userRoleList = CommonSysUserRoleService::getListByUserId($id);
        $data['roleIds'] = count($userRoleList) ? array_column($userRoleList, 'role_id') : [];

        return $data;
    }

    /**
     * 删除
     * @param  string  $ids  数据ID
     * @return json
     */
    public static function destroy($ids){
        if(!empty($ids)){
            SysUserModel::deleteById($ids);
        }
    }

    /**
     * 用户登录
     * @param  array  $data  请求参数
     * @return array
     */
    public static function login($data){
        $user = SysUserModel::getByUsername($data['username']);
        if(empty($user) || !comparePassword($data['password'], $user['password'])){
            return failure(ErrorEnum::USERNAME_OR_PASSWORD_IS_ERROR_CODE, ErrorEnum::USERNAME_OR_PASSWORD_IS_ERROR_DESC);
        }

        if($user['status'] == BaseStatusEnum::DISABLED){
            return failure(ErrorEnum::USERNAME_IS_DISABLED_CODE, ErrorEnum::USERNAME_IS_DISABLED_DESC);
        } 
       
        $user->login_date = date('Y-m-d H:i:s',time());
        $user->login_ip = getClientIp();
        $user->save();

        if ($user->user_type == 100) {
            // 超级管理，直接查看所有菜单
            $menuList = CommonSysMenuService::list(['status' => BaseStatusEnum::ENABLED]);
        } else {
            // 获取菜单权限
            $menuList = CommonSysUserRoleService::list(['user_id' => $user->id]);
        }

        session('userInfo', $user->toArray());
        session('user_id', $user->id);
        session('menuList', treeData($menuList, 0));
    }

    /**
     * 修改密码
     * @param  array  $data  更新的数据
     * @return json
     */
    public static function changePasswrod($data){
        $sysUser = SysUserModel::find($data['id']);
        if(!$sysUser){
            return failure(ErrorEnum::USERNAME_IS_NOT_EXIST_CODE, ErrorEnum::USERNAME_IS_DISABLED_DESC);
        }

        $data['password'] = createPassword($data['password']);
        $sysUser->save($data);
    }

    
}